<?php

/**
 * +----------------------------------------------------------------------
 * | TickyPHP [ This is a freeware ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2015 All rights reserved.
 * +----------------------------------------------------------------------
 * | Author: luomingui <e-mail:minguiluo@163.com> <QQ:271391233>
 * | SVN: $Id: Auth.php 29529 2018-2-12 luomingui $
 * +----------------------------------------------------------------------
 * | Description：权限认证类
 *  $auth=new Auth();
 *  $auth->check('规则名称','用户id')
 * +----------------------------------------------------------------------
 */
/*

  -- ----------------------------
  -- Table structure for tky_authrole
  -- ----------------------------
  DROP TABLE IF EXISTS `tky_auth_role`;
  CREATE TABLE `tky_auth_role` (
  `roleid` mediumint(8) unsigned NOT NULL AUTO_INCREMENT COMMENT '编号',
  `title` char(30) NOT NULL DEFAULT '' COMMENT '名称',
  `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '状态',
  `rules` text COMMENT '规则',
  PRIMARY KEY (`roleid`)
  ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COMMENT='角色';

  -- ----------------------------
  -- Records of tky_authrole
  -- ----------------------------
  INSERT INTO `tky_auth_role` VALUES ('1', '管理员', '1', '80,79,78,77,76,75,74,73,72,71,70,69,68,67,66,65,64,63,62,61,60,59,58,57,56,55,54,53,52,51,50,49,48,47,46,45,44,43,42,41,40,39,38,37,36,35,34,33,32,31,30,29,28,27,26,25,24,23,22');
  INSERT INTO `tky_auth_role` VALUES ('2', '测试用户', '0', '80,79');

  -- ----------------------------
  -- Table structure for tky_authrolemember
  -- ----------------------------
  DROP TABLE IF EXISTS `tky_auth_role_member`;
  CREATE TABLE `tky_auth_role_member` (
  `uid` mediumint(8) unsigned NOT NULL DEFAULT '0' COMMENT '用户编号',
  `roleid` mediumint(8) unsigned NOT NULL DEFAULT '0' COMMENT '组编号',
  UNIQUE KEY `uid_role_id` (`uid`,`roleid`)
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户角色';

  -- ----------------------------
  -- Records of tky_authrolemember
  -- ----------------------------
  INSERT INTO `tky_auth_role_member` VALUES ('1', '1');

  -- ----------------------------
  -- Table structure for tky_authrule
  -- ----------------------------
  DROP TABLE IF EXISTS `tky_auth_rule`;
  CREATE TABLE `tky_auth_rule` (
  `ruleid` mediumint(8) unsigned NOT NULL AUTO_INCREMENT COMMENT '编号',
  `module` varchar(20) NOT NULL DEFAULT '' COMMENT '规则所属module',
  `type` tinyint(1) NOT NULL DEFAULT '1' COMMENT '类型 1-url;2-主菜单',
  `name` char(80) NOT NULL DEFAULT '' COMMENT '规则唯一英文标识',
  `title` char(20) NOT NULL DEFAULT '' COMMENT '规则中文描述',
  `regex` char(100) NOT NULL DEFAULT '' COMMENT '规则表达式',
  `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '状态',
  PRIMARY KEY (`ruleid`)
  ) ENGINE=InnoDB AUTO_INCREMENT=80 DEFAULT CHARSET=utf8 COMMENT='规则表';

 */

namespace ticky;

use ticky\config;

class autht {

    //默认配置
    protected $config = array(
        'AUTH_ON' => true, // 认证开关
        'AUTH_TYPE' => 1, // 认证方式，1为实时认证；2为登录认证。
        'AUTH_GROUP' => 'auth_role', // 用户组数据表名
        'AUTH_GROUP_ACCESS' => 'auth_role_member', // 用户-用户组关系表
        'AUTH_RULE' => 'auth_rule', // 权限规则表
        'AUTH_USER' => 'member'    // 用户信息表
    );
    protected $prefix;

    public function __construct() {

        $config = config::get('db');
        $driver = $config['driver'];
        $config = $config[$driver];
        $this->prefix = $config['prefix'];

        $this->config['AUTH_GROUP'] = $this->prefix . $this->config['AUTH_GROUP'];
        $this->config['AUTH_RULE'] = $this->prefix . $this->config['AUTH_RULE'];
        $this->config['AUTH_USER'] = $this->prefix . $this->config['AUTH_USER'];
        $this->config['AUTH_GROUP_ACCESS'] = $this->prefix . $this->config['AUTH_GROUP_ACCESS'];
    }

    /**
     * 检查权限
     * @param name string|array  需要验证的规则列表,支持逗号分隔的权限规则或索引数组
     * @param uid  int           认证用户的id
     * @param string mode        执行check的模式
     * @param relation string    如果为 'or' 表示满足任一条规则即通过验证;如果为 'and'则表示需满足所有规则才能通过验证
     * @return boolean           通过验证返回true;失败返回false
     */
    public function check($name, $uid, $type = 1, $mode = 'url', $relation = 'or') {
        $authList = $this->getAuthList($uid, $type); //获取用户需要验证的所有有效规则列表
        if (is_string($name)) {
            $name = strtolower($name);
            if (strpos($name, ',') !== false) {
                $name = explode(',', $name);
            } else {
                $name = array($name);
            }
        }
        $list = array(); //保存验证通过的规则名
        if ($mode == 'url') {
            $REQUEST = unserialize(strtolower(serialize($_REQUEST)));
        }
        foreach ($authList as $auth) {
            $query = preg_replace('/^.+\?/U', '', $auth);
            if ($mode == 'url' && $query != $auth) {
                parse_str($query, $param); //解析规则中的param
                $intersect = array_intersect_assoc($REQUEST, $param);
                $auth = preg_replace('/\?.*$/U', '', $auth);
                if (in_array($auth, $name) && $intersect == $param) {  //如果节点相符且url参数满足
                    $list[] = $auth;
                }
            } else if (in_array($auth, $name)) {
                $list[] = $auth;
            }
        }
        if ($relation == 'or' and ! empty($list)) {
            return true;
        }
        $diff = array_diff($name, $list);
        if ($relation == 'and' and empty($diff)) {
            return true;
        }
        return false;
    }

    /**
     * 获得权限列表
     * @param integer $uid  用户id
     * @param integer $type
     */
    protected function getAuthList($uid, $type) {
        static $_authList = array(); //保存用户验证通过的权限列表
        $t = implode(',', (array) $type);
        if (isset($_authList[$uid . $t])) {
            return $_authList[$uid . $t];
        }

        if ($this->config['AUTH_TYPE'] == 2 && isset($_SESSION['_AUTH_LIST_' . $uid . $t])) {
            return $_SESSION['_AUTH_LIST_' . $uid . $t];
        }

        //读取用户所属用户组
        $groups = $this->getGroups($uid);
        $ids = array(); //保存用户所属用户组设置的所有权限规则id
        foreach ($groups as $g) {
            $ids = array_merge($ids, explode(',', trim($g['rules'], ',')));
        }
        $ids = array_unique($ids);
        if (empty($ids)) {
            $_authList[$uid . $t] = array();
            return array();
        }

        $map = array(
            'ruleid' => array('in', $ids),
            'type' => $type,
            'status' => 1,
        );
        //读取用户组所有权限规则
        $rules = db($this->config['AUTH_RULE'])->where($map)->field('regex,name')->select();

        //循环规则，判断结果。
        $authList = array();   //
        foreach ($rules as $rule) {
            if (!empty($rule['condition'])) { //根据condition进行验证
                $user = $this->getUserInfo($uid); //获取用户信息,一维数组

                $command = preg_replace('/\{(\w*?)\}/', '$user[\'\\1\']', $rule['regex']);
                //dump($command);//debug
                (eval('$condition=(' . $command . ');'));
                if ($condition) {
                    $authList[] = strtolower($rule['name']);
                }
            } else {
                //只要存在就记录
                $authList[] = strtolower($rule['name']);
            }
        }
        $_authList[$uid . $t] = $authList;
        if ($this->config['AUTH_TYPE'] == 2) {
            //规则列表结果保存到session
            $_SESSION['_AUTH_LIST_' . $uid . $t] = $authList;
        }
        return array_unique($authList);
    }

    /**
     * 根据用户id获取用户组,返回值为数组
     * @param  uid int     用户id
     * @return array       用户所属的用户组 array(
     *     array('uid'=>'用户id','group_id'=>'用户组id','title'=>'用户组名称','rules'=>'用户组拥有的规则id,多个,号隔开'),
     *     ...)
     */
    public function getGroups($uid) {
        static $groups = array();
        if (isset($groups[$uid])) {
            return $groups[$uid];
        }

        $user_groups = db($this->config['AUTH_GROUP_ACCESS'] . ' a')
                ->field('a.uid,a.roleid,g.title,g.rules')
                ->join($this->config['AUTH_GROUP'] . " g on a.roleid=g.roleid")
                ->where("a.uid='$uid' and g.status='1'")
                ->select();
        $groups[$uid] = $user_groups ?: array();
        return $groups[$uid];
    }

    /**
     * 获得用户资料,根据自己的情况读取数据库
     */
    protected function getUserInfo($uid) {
        static $userinfo = array();
        if (!isset($userinfo[$uid])) {
            $userinfo[$uid] = db($this->config['AUTH_USER'])->where(['uid' => $uid])->field('regex,name')->find();
        }
        return $userinfo[$uid];
    }

    //初始化权限数据
    public function init_perm() {
        $modules = array('admin');  //模块名称
        $i = 0;
        //delete from tky_authrule;update tky_authrole set rules='';
        foreach ($modules as $module) {
            $all_controller = $this->getController($module);
            //debug($all_controller);
            foreach ($all_controller as $controller) {
                $all_action = $this->getAction($module, $controller);
                if (isset($all_action)) {
                    //debug($all_action);
                    foreach ($all_action as $action) {
                        $controller = str_replace('controller', '', $controller);
                        $data[$i]['module'] = $module;
                        $data[$i]['controller'] = $controller;
                        $data[$i]['action'] = $action;
                        //入库
                        if (!empty($module) && !empty($controller) && !empty($action)) {
                            $rule_name = $module . '-' . $controller . '-' . $action;
                            $rule = db($this->config['AUTH_RULE'])->where("name='" . strtolower($rule_name) . "'")->find();
                            if (!$rule) {

                                $idata = array();
                                $idata['module'] = strtolower($module . '-' . $controller);
                                $idata['type'] = "1";
                                $idata['name'] = strtolower($rule_name);
                                $idata['title'] = L(strtolower($rule_name));
                                $idata['regex'] = "";
                                $idata['status'] = "1";

                                db($this->config['AUTH_RULE'])->add($idata);
                            }
                        }
                        $i++;
                    }
                }
            }
        }
        return true;
    }

    //获取所有控制器名称
    private function getController($module) {
        if (empty($module)) {
            return null;
        }
        $module_path = APP_PATH . '/' . $module . '/controller/';  //控制器路径
        if (!is_dir($module_path)) {
            return null;
        }
        $module_path .= '/*.php';
        $ary_files = glob($module_path);
        foreach ($ary_files as $file) {
            if (is_dir($file)) {
                continue;
            } else {
                //排除部分控制器
                $inherents_functions = array('auth', 'call', 'login', 'logout', 'index');
                $filename = basename($file, '.php');
                if (!in_array($filename, $inherents_functions)) {
                    $files[] = $filename;
                }
            }
        }
        return $files;
    }

    //获取所有方法名称
    protected function getAction($module, $controller) {
        if (empty($controller)) {
            return null;
        }
        $file = APP_PATH . '/' . $module . '/controller/' . $controller . '.php';
        if (file_exists($file)) {
            $content = file_get_contents($file);
            preg_match_all("/.*?public.*?function(.*?)\(.*?\)/i", $content, $matches);
            $functions = $matches[1];
            //排除部分方法
            $inherents_functions = array('_initialize', '__construct', 'getActionName', 'isAjax', 'display', 'show', 'fetch', 'buildHtml', 'assign', '__set', 'get', '__get', '__isset', '__call', 'error', 'success', 'ajaxReturn', 'redirect', '__destruct', '_empty');
            foreach ($functions as $func) {
                $func = trim($func);
                if (!in_array($func, $inherents_functions)) {
                    $customer_functions[] = $func;
                }
            }
            return $customer_functions;
        }
        return null;
    }

}
